<template>
  <div class="app-container">
    <el-card v-loading="loading" class="box-card">
      <div slot="header" class="clearfix">

        <span style="margin-left: 20px"> 当前搜索词:<em style="color: red">{{ query }}</em> </span>
        <span v-if="translate_query.length > 0">{{ translate_query }}</span>
        <el-tag type="danger" style="margin-left: 50px;">当前:{{ current_index }} 总共:{{ keywords.length }}</el-tag>
        <el-button style="margin-left: 50px;" type="success" @click="GetNextPage" @keyup.down="GetNextPage">下一个</el-button>

        <el-button style="margin-left: 10px;" type="warning" @click="GetPrevPage" @keyup.up="GetPrevPage">上一个</el-button>
        <el-button v-if="keywords[current_index] && keywords[current_index].isStar" style="margin-left: 20px;"type="warning" icon="el-icon-star-off" circle @click="handleStar" />
        <el-button v-else style="margin-left: 20px;" icon="el-icon-star-off" circle @click="handleStar" />
        <el-button
          type=""
          style="float: right;"
          @click="dialogVisible = true"
        >
          导入关键词</a>
        </el-button>
        <div v-if="keywords.length > 0 && b_id">
          <br>
          <el-tag>搜索量:{{ keywords[current_index].search_volumn }}</el-tag>
          <el-tag>难度:{{ keywords[current_index].difficulty }}</el-tag>
          <el-tag>CPC:{{ keywords[current_index].cpc }}</el-tag>
          <el-tag>来源链接:<a :href="keywords[current_index].url" target="_blank">{{ keywords[current_index].url }}</a></el-tag>
        </div>
      </div>
      <el-row>
        <el-col :span="18">
          <div
            v-for="item in searchDatas"
            class="text item"
            style="margin-right: 5px;
          font-size: 14px;
          overflow: hidden;
          margin-bottom: 12px;
          padding: 3px 5px 3px 0px;
          margin-left: 0px;"
          >
            <div style="display: inline-block;">
              <span style="margin-right: 10px;display: block;">
                <img :src="item.image" style="height: 100px;width:100px"></span>
            </div>
            <div style="padding-left: 10px;display: inline-block;">
              <p class="title" @mouseover="handleTranslate(item)" v-html="item.title" />
              <p style="margin: 0px;">{{ item.translated_title }}</p>
              <p class="desc" v-html="item.content" />
              <span class="a"><a :href="item.url" target="_blank">{{ item.url }}</a></span>
              <span class="a"><a :href="'https://www.similarweb.com/website/'+item.url" target="_blank">similarweb</a></span>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <el-table
            :data="starKeywords"
            style="width: 100%"
          >
            <el-table-column
              prop="keyword"
              label="已标星关键词"
              width="180"
            />
            <el-table-column
              prop="search_volumn"
              label="搜索量"
              width="100"
            />
            <el-table-column
              fixed="right"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleStarSearch(scope.row)">搜索</el-button>
                <el-button type="text" size="small" @click="handleStar(scope.row.keyword)">取消标记</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      title="输入关键词"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>请输入关键词多个词用逗号分隔</span>
      <el-input v-model="keywordstext" type="textarea" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleKeywords">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<style scoped>
  .app-container >>> .el-select .el-input {
    width: 130px;
  }

  .app-container >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .app-container >>> .text {
    font-size: 14px;
  }

  .app-container >>> .text p.title {
    font-weight: bold;
    font-weight: 600;
  }

  .app-container >>> .text p.desc {
    font-size: 10px;
  }

  .app-container >>> .text em {
    color: red;
  }

  .app-container >>> .text span.a {
    color: #3A7734;
  }

  .app-container >>> .item {
    margin-bottom: 1px;
  }

  .app-container >>> .clearfix:before,
  .app-container >>> .clearfix:after {
    display: table;
    content: "";
  }

  .app-container >>> .clearfix:after {
    clear: both
  }
</style>
<script>
import { Post, GetKewords, ReadedTaggle, StarTaggle } from '@/api/eco/search'
import { Translate } from '@/api/baidu'
import Cookies from 'js-cookie'

export default {
  data() {
    return {
      query: '',
      keywords: [],
      starKeywords: [],
      current_index: 0,
      keywordstext: 'amazon',
      dialogVisible: false,
      searchDatas: [],
      loading: false,
      translate_query: '',
      tempdata: []
    }
  },
  computed: {
    b_id: function() {
      return this.$route.query.b_id
    }
  },
  created() {
    if (!this.b_id) {
      this.keywordstext = Cookies.get('searchkeywords') || ''
      this.keywords = this.keywordstext.split(',')
      this.current_index = parseInt(Cookies.get('searchkeywordsindex')) || 0
      this.onSubmit()
    } else {
      GetKewords({ b_id: this.b_id }).then((response) => {
        this.keywords = response.data
        this.onSubmit()
      })

      GetKewords({ b_id: this.b_id, isStar: true }).then((response) => {
        this.starKeywords = response.data
        this.onSubmit()
      })
    }
  },
  methods: {
    onSubmit() {
      if (this.keywords.length > 0) {
        if (this.b_id) { this.query = this.keywords[this.current_index].keyword } else { this.query = this.keywords[this.current_index] }
      }
      if (!this.query.length) {
        return
      }
      this.loading = true

      Post(JSON.stringify({ query: this.query, page: 1 })).then((response) => {
        this.searchDatas = response.data.map(v => {
          this.$set(v, 'translated_title', '')
          return v
        })
        this.loading = false
        if (!this.b_id) {
          Cookies.set('searchkeywordsindex', this.current_index)
        }

        // 翻译所有标题
        // for (const i in this.searchDatas.slice(0, 3)) {
        //   // this.$nextTick(() => {
        //   let msg = this.searchDatas[i].title
        //   msg = msg.replace(/<\/?[^>]*>/g, ''); // 去除HTML Tag
        //   msg = msg.replace(/[|]*\n/, '') // 去除行尾空格
        //   msg = msg.replace(/&npsp;/ig, ''); // 去掉npsp
        //   // this.searchDatas[0].translated_title = 'aaaa'
        //   Translate({ q: msg }).then((response) => {
        //     this.searchDatas[i].translated_title = response.data.trans_result[0].dst
        //   });
        // }
      })
      Translate({ q: this.query }).then((response) => {
        this.translate_query = response.data.trans_result[0].dst
      })
    },
    handleKeywords() {
      if (this.keywordstext.length <= 0) {
        return '请输入关键词'
      }

      this.dialogVisible = false
      this.keywords = this.keywordstext.split(',')
      this.current_index = 0
      Cookies.set('searchkeywords', this.keywordstext)
      this.onSubmit()
    },
    handleStar(value) {
      console.log(value)
      if (typeof value !== 'string') {
        value = this.query
      }
      StarTaggle({ keyword: value }).then((response) => {
        GetKewords({ b_id: this.b_id, isStar: true }).then((response) => {
          this.starKeywords = response.data
        })
      })
    },
    handleStarSearch(row) {
      this.loading = true
      this.query = row.keyword
      Post(JSON.stringify({ query: this.query, page: 1 })).then((response) => {
        this.searchDatas = response.data.map(v => {
          this.$set(v, 'translated_title', '')
          return v
        })
        this.loading = false
      })
      Translate({ q: this.query }).then((response) => {
        this.translate_query = response.data.trans_result[0].dst
      })
    },
    handleTranslate(row) {
      if (!row.translated_title) {
        row.translated_title = 'translating...'
        let msg = row.title
        msg = msg.replace(/<\/?[^>]*>/g, '') // 去除HTML Tag
        msg = msg.replace(/[|]*\n/, '') // 去除行尾空格
        msg = msg.replace(/&npsp;/ig, '') // 去掉npsp
        msg = msg.replace(/&amp;/ig, '') // 去掉npsp &#39
        msg = msg.replace(/&#39;/ig, '') // 去掉npsp
        msg = msg.replace(/\+/ig, '') // 去掉npsp
        msg = msg.replace(/[^\w]/, '')
        Translate({ q: msg }).then((response) => {
          if ('error_code' in response.data) {
            row.translated_title = 'translate failed'
          } else { row.translated_title = response.data.trans_result[0].dst }
        })
      }
    },
    GetNextPage() {
      this.current_index = this.current_index + 1

      if (this.current_index > this.keywords.length) {
        alert('已经是最后一个词了')
        this.current_index = this.current_index - 1
        return
      }
      ReadedTaggle({ keyword: this.query }).then((response) => {
        console.log('tag success')
      })
      this.onSubmit()
    },
    GetPrevPage() {
      if (this.current_index <= 0) {
        alert('已经是最第一个词了')
        return
      }
      this.current_index = this.current_index - 1
      this.onSubmit()
    }

  }

}

</script>
